/**
 * 
 */
package es.aradesh.ministryassist.logic.ministry;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.provider.BaseColumns;

import es.aradesh.ministryassist.db.DbAdapter;
import es.aradesh.ministryassist.db.HomeColumns;

/**
 * @author xmorales
 * 
 */
public class HomeBuilder {
	public static long createHome(DbAdapter db, String name, int status,
			Street strParent, Home building, String owner) {
		long buildingId = building != null ? building.getId()
				: Home.NOT_IN_BUILDING;
		long id = -1;
		if (!"".equals(name)) {
			if (name.matches("[0-9]*"))
				// name is a number and needs a 4 number mask to allow a correct orderBy filter in DB
				while (name.length() < 4)
					name = "0".concat(name);
			id = db.insertHome(name, strParent.getId(), buildingId, 0, 0,
					status, owner);
		}
		return id;
	}

	public static Home getHomeById(DbAdapter db, long id) {
		Home result = null;
		ContentValues cv = db.selectById(DbAdapter.TABLE_HOME, id);
		if (cv.getAsInteger(HomeColumns.STATUS).intValue() == Home.STATUS_BUILDING) {
			// Is a building
			result = new Home(id, cv.getAsInteger(HomeColumns.LEVELS)
					.intValue(), cv.getAsInteger(HomeColumns.DOORS)
					.intValue(), cv.getAsString(HomeColumns.NAME),
					StreetBuilder.getStreetById(db, cv.getAsLong(
							HomeColumns.STREET_ID).longValue()));
			setBuildingChildren(db, result);
		} else {
			// Is a home
			result = new Home(id, StreetBuilder.getStreetById(db, cv.getAsLong(
					HomeColumns.STREET_ID).longValue()), null, cv
					.getAsString(HomeColumns.NAME), cv.getAsInteger(
							HomeColumns.STATUS).intValue(), cv
					.getAsString(HomeColumns.OWNER));
		}
		return result;
	}

	public static List<Home> getHomesByStreet(DbAdapter db, Street parent) {
		List<Home> result = new ArrayList<Home>();
		Home temp = null;
		String[] cols = new String[] { BaseColumns._ID };
		Cursor c = db.selectTable(DbAdapter.TABLE_HOME, cols,
				HomeColumns.STREET_ID + " = " + parent.getId(),
				HomeColumns.NAME);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			temp = getHomeById(db, c.getLong(c
					.getColumnIndex(BaseColumns._ID)));
			c.moveToNext();
			result.add(temp);
		}
		return result;
	}

	private static void setBuildingChildren(DbAdapter db, Home building) {
		Home temp = null;
		String[] cols = new String[] { BaseColumns._ID };

		Cursor c = db.selectTable(DbAdapter.TABLE_HOME, cols,
				HomeColumns.BUILDING_ID + " = " + building.getId(), null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			temp = getHomeById(db, c.getLong(c
					.getColumnIndex(BaseColumns._ID)));
			temp.setBuilding(building);
			building.addFlat(temp);
			c.moveToNext();
		}
	}

}
